/*
 *  Copyright (c) 2013 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.yuntongxun.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
package com.yuntongxun.ecdemo.ui.chatting;

import java.io.InvalidClassException;
import java.util.ArrayList;
import java.util.List;



import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.flyco.systembar.SystemBarHelper;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.dialog.ECProgressDialog;
import com.yuntongxun.ecdemo.common.utils.CrashHandler;
import com.yuntongxun.ecdemo.common.utils.ECPreferenceSettings;
import com.yuntongxun.ecdemo.common.utils.ECPreferences;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.common.utils.ToastUtil;
import com.yuntongxun.ecdemo.ui.ECFragmentActivity;
import com.yuntongxun.ecdemo.ui.MeetingMsgReceiver;
import com.yuntongxun.ecdemo.ui.SDKCoreHelper;
import com.yuntongxun.ecdemo.ui.chatting.view.CCPChattingFooter2;
import com.yuntongxun.ecdemo.ui.meeting.MeetingBaseActivity;
import com.yuntongxun.ecdemo.ui.meeting.MeetingHelper;
import com.yuntongxun.ecdemo.ui.meeting.VoiceMeetingActivity;
import com.yuntongxun.ecdemo.voicechat.bean.PostResult;
import com.yuntongxun.ecdemo.voicechat.comman.EventBusTags;
import com.yuntongxun.ecdemo.voicechat.comman.GroupChatContacts;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.ECMeetingManager;
import com.yuntongxun.ecsdk.ECMessage;
import com.yuntongxun.ecsdk.meeting.ECMeeting;
import com.yuntongxun.ecsdk.meeting.ECMeetingMember;
import com.yuntongxun.ecsdk.meeting.intercom.ECInterPhoneMeetingMsg;
import com.yuntongxun.ecsdk.meeting.voice.ECVoiceMeetingMsg;

import de.greenrobot.event.EventBus;

/**
 * @author 容联•云通讯
 * @date 2014-12-9
 * @version 4.0
 */
public class ChattingActivity extends ECFragmentActivity implements
		ChattingFragment.OnChattingAttachListener,MeetingHelper.OnMeetingCallback,MeetingMsgReceiver.OnVoiceMeetingMsgReceive{

	private static final String TAG = "ECSDK_Demo.ChattingActivity";
	public ChattingFragment mChattingFragment;
	private MyReceiver myReceiver;
	private double amplitude;

	//聊天会话中出现的会议id
	List<String> meetingNoList=new ArrayList<>();

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		LogUtil.d(TAG, "chatting ui dispatch key event :" + event);
		if (mChattingFragment != null
				&& mChattingFragment.onKeyDown(event.getKeyCode(), event)) {
			return true;
		}

		return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onResume() {
		super.onResume();
//		CrashHandler.getInstance().setContext(this);

		IntentFilter filter1 = new IntentFilter();

		filter1.addAction("com.yuntongxun.ecdemo.removemember");
		filter1.addAction(SDKCoreHelper.ACTION_KICK_OFF);

		registerReceiver(myReceiver, filter1);
		MeetingHelper.addInterPhoneCallback(this);

		if(recipients != null && recipients.toLowerCase().startsWith("g")){
			MeetingHelper.queryMeetingsAfterStopVoicMeeting(ECMeetingManager.ECMeetingType.MEETING_MULTI_VOICE);
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(myReceiver);
		MeetingHelper.removeInterPhoneCallback(this);
	}



	@Override
	public void onMeetings(List<ECMeeting> list) {

	}

	@Override
	public void onMeetingMembers(List<? extends ECMeetingMember> members) {
	}

//	String meetingNo="";

	@Override
	public void onMeetingStart(String meetingNo) {

	}

	@Override
	public void onMeetingDismiss(String meetingNo) {
		mChattingFragment.dismissPostingDialog();
	}

	@Override
	public void onError(int type, ECError e) {

	}

	@Override
	public void onReceiveVoiceMeetingMsg(ECVoiceMeetingMsg msg) {

	}

	@Override
	public void onReceiveInterPhoneMeetingMsg(ECInterPhoneMeetingMsg msg) {

	}

	public double getAmplitude() {
		return this.amplitude;
	}

	public void setAmplitude(double amplitude) {
		this.amplitude = amplitude;
	}

	public class MyReceiver extends BroadcastReceiver
	{
		// 可用Intent的getAction()区分接收到的不同广播
		@Override
		public void onReceive(Context arg0, Intent intent)
		{
			if(intent==null){
				return;
			}
			if (intent.getAction().equals(SDKCoreHelper.ACTION_KICK_OFF)
					|| intent.getAction().equals(
							"com.yuntongxun.ecdemo.removemember"))
				finish();
		}
	}
	String recipients;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		LogUtil.d(TAG, "onCreate");
		super.onCreate(null);
		getWindow().setFormat(PixelFormat.TRANSPARENT);
		setupSystemBar();
		myReceiver = new MyReceiver();
		recipients = getIntent().getStringExtra(
				ChattingFragment.RECIPIENTS);
		EventBus.getDefault().register(this);
		startThread();//判断是否群聊还存在

		if (recipients == null) {
			finish();
			LogUtil.e(TAG, "recipients is null !!");
			return;
		}
		setContentView(R.layout.chattingui_activity_container);
		mChattingFragment = new ChattingFragment();
		Bundle bundle = getIntent().getExtras();
		bundle.putBoolean(ChattingFragment.FROM_CHATTING_ACTIVITY, true);
		bundle.putString(ChattingFragment.CUSTOMER_LITTLE_INFO,recipients);
		mChattingFragment.setArguments(bundle);
		getSupportFragmentManager().beginTransaction()
				.add(R.id.ccp_root_view, mChattingFragment).commit();
		onActivityCreate();

		if (isChatToSelf(recipients) || isPeerChat(recipients)) {
			AppPanelControl.setShowVoipCall(false);
		}
		MeetingMsgReceiver.addVoiceMeetingListener(this);




	}

	protected void doStartMeetingActivity(ECMeeting meeting ,String pass , boolean callin) {
		Intent intent = new Intent(this , VoiceMeetingActivity.class);
		intent.putExtra(VoiceMeetingActivity.EXTRA_MEETING , meeting);
		if(!TextUtils.isEmpty(pass)) {
			intent.putExtra(VoiceMeetingActivity.EXTRA_MEETING_PASS , pass);
		}
		intent.putExtra(VoiceMeetingActivity.EXTRA_CALL_IN , callin);
		startActivity(intent) ;
	}

	private void setupSystemBar(){

		SystemBarHelper.tintStatusBar(this, getResources().getColor(R.color.toolbar_bg));

	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		LogUtil.d(TAG, "chatting ui on key down, " + keyCode + ", " + event);
		
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0&&CCPChattingFooter2.isRecording) {
			// do nothing.
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		LogUtil.d(TAG, "chatting ui on key up");
		return super.onKeyUp(keyCode, event);
	}

	public boolean isPeerChat() {
		if (mChattingFragment != null) {
			return mChattingFragment.isPeerChat();
		}
		return false;
	}

	public boolean isChatToSelf(String sessionId) {

		String userId = CCPAppManager.getUserId();
		return sessionId != null
				&& (sessionId.equalsIgnoreCase(userId) ? true : false);
	}

	public boolean isPeerChat(String sessionId) {

		return sessionId.toLowerCase().startsWith("g");
	}

	@Override
	public void onChattingAttach() {
		LogUtil.d(TAG, "onChattingAttach");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
		MeetingHelper.removeInterPhoneCallback(this);
		MeetingMsgReceiver.removeVoiceMeetingListener(this);
	}

	private ECProgressDialog mPostingdialog;
	List<ECMeeting> list;
	ECMeeting ecMeeting;
	public void onEvent(PostResult postResult){
		switch (postResult.getTag()){
			case EventBusTags.MSG:
				ToastUtil.showMessage((String)postResult.getResult());
				break;
			case EventBusTags.SHOW_DIALOG:
				mPostingdialog = new ECProgressDialog(this, "Waiting");
            	mPostingdialog.show();
				break;
			case EventBusTags.CANCEL_DIALOG:
				mPostingdialog.dismiss();
				break;
			case EventBusTags.MEETING_NO:
				String meetId=(String)postResult.getResult();

				if (!TextUtils.isEmpty(meetId)){
					if (meetingNoList.size()==0){
						meetingNoList.add(meetId);
					}else{
						boolean add=true;
						for (int i=0;i<meetingNoList.size();i++){
							if (meetingNoList.get(i).equals(meetId)){
								add=false;
							}
						}

						if (add){
							meetingNoList.add(meetId);
						}
					}
				}
				MeetingHelper.queryMeetingsAfterStopVoicMeeting(ECMeetingManager.ECMeetingType.MEETING_MULTI_VOICE);

				break;

			case EventBusTags.QUERY_MEETING_LIST:

				if (meetingNoList.size()==0){
					return;
				}
				list=(List<ECMeeting>) postResult.getResult();
				boolean isExits = false;
				if (list!=null&&list.size()>0&&meetingNoList!=null&&meetingNoList.size()>0){

					for (int i = 0; i < list.size(); i++) {
						Log.e("list"+i,list.get(i).getMeetingNo());
						for (int j=0;j<meetingNoList.size();j++){
							Log.e("meetingNoList"+j,meetingNoList.get(j));
							if (list.get(i).getMeetingNo().equals(meetingNoList.get(j))) {
								isExits = true;
								ecMeeting = list.get(i);
								break;
							}
						}
					}

					if (isExits) {
						mChattingFragment.addMeetingBtn.setVisibility(View.VISIBLE);
						mChattingFragment.setEcMeeting(ecMeeting);
					} else {
						mChattingFragment.addMeetingBtn.setVisibility(View.GONE);
					}
				}else{
					mChattingFragment.addMeetingBtn.setVisibility(View.GONE);
				}
				break;
			case EventBusTags.MEETING_CREATE:
				String meetingNo=(String)postResult.getResult();
				Log.e("metingNo",meetingNo);
				mChattingFragment.dismissPostingDialog();
				mChattingFragment.startVoice(meetingNo);
				String message= GroupChatContacts.getConfContact(recipients,meetingNo);
				mChattingFragment.handlesendConfMessage(message);
				break;
			case EventBusTags.MEETING_CLOSE:
				meetingNoList.clear();
				message= GroupChatContacts.getConfContact(recipients,"");
				mChattingFragment.handlesendConfMessage(message);
				break;
		}
	}

	private Handler mHandler;
	Runnable runnable;
	private void startThread(){
		if (mHandler==null){
			mHandler = new Handler();
			runnable=new Runnable() {
				@Override
				public void run()
				{
					if (mHandler!=null){
						MeetingHelper.queryMeetingsAfterStopVoicMeeting(ECMeetingManager.ECMeetingType.MEETING_MULTI_VOICE);
						mHandler.postDelayed(this, 2000);
					}
				}
			};
			mHandler.post(runnable);
		}
	}
}